/*
 * -- BaiduRateClient.java --
 * 
 * Copyright 2011, Kyan He <kyan.ql.he@gmail.com>
 * 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package im.kyan.android.googlefight;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class BaiduRateClient {
    private static final String TAG = "RateEngine";
    
    private static final String HOST = "http://www.baidu.com/";
    
    private static final String REGEX = "<span class=\"nums\".*>找到相关结果(约)?([0-9,]+)个</span>";
    
    private HttpClient mHttpClient;
    
    public BaiduRateClient() {
        new ConnectThread().start();
    }
    
    /*
     * keep a connection with server
     */
    class ConnectThread extends Thread {
        
        @Override
        public void run() {
            mHttpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(HOST + "favicon.ico");
            
            for (Header h : httpget.getAllHeaders()) {
                Log.d(TAG, h.toString());
            }
            
            HttpResponse response;
            try {
                response = mHttpClient.execute(httpget);
                
                if (200 != response.getStatusLine().getStatusCode()) {
                    Log.d(TAG, "oh no");
                }
                
                HttpEntity entity = response.getEntity();
                Log.d(TAG, "Content-length: " + entity.getContentLength());
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    byte[] tmp = new byte[2048];
                    while ((instream.read(tmp)) != -1) {
                    }
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d(TAG, "IO ready");
            Log.d(TAG, "rate: " + getRate("fuck"));
        }
    }
    
    public long getRate(String key) {
        
        /* validate key */
        key = key.replaceAll(" ", "%20");
        HttpGet httpget = new HttpGet(HOST + "s?wd=" + key);
        HttpResponse response;
        try {
            response = mHttpClient.execute(httpget);
            
            if (200 != response.getStatusLine().getStatusCode()) {
                Log.d(TAG, "oh no");
                return 0;
            }
            
            HttpEntity entity = response.getEntity();
            Log.d(TAG, "Content-length: " + entity.getContentLength());
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int bytesread = 0;
            if (entity != null) {
                InputStream instream = entity.getContent();
                byte[] buf = new byte[4096];
                int sz;
                
                while ((sz = instream.read(buf)) != -1) {
                    bytesread += sz;
                    os.write(buf, 0, sz);
                    Log.d(TAG, " matching" + sz);
                }
                
            }
            
            Log.d(TAG, " matching");
            String str = new String(os.toByteArray());
            Log.d(TAG, str.length() + " / " + bytesread);
            Pattern p = Pattern.compile(new String(REGEX.getBytes("GB2312")));
            Matcher matcher = p.matcher(str);
            
            while (matcher.find()) {
                Log.d(TAG, "#" + matcher.groupCount() + ":" + matcher.group());
                
                String s = matcher.group(2);
                
                long rate;
                try {
                    rate = Integer.parseInt(s.replaceAll(",", ""));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    return 0;
                }
                Log.d(TAG, "" + rate);
                return rate;
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Log.d(TAG, "IO ready");
    }
}
